package com.haier.uos.weather.city.service.impl;

import com.haier.uos.weather.city.service.ICityDataService;
import com.haier.uos.weather.city.uitl.XmlBuilder;
import com.haier.uos.weather.city.vo.City;
import com.haier.uos.weather.city.vo.CityList;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

@Service
public class CityDataService implements ICityDataService {
    @Override
    public List<City> getCities() {
        List<City> cities = null;
        try {
            CityList cityList = (CityList) XmlBuilder.xmlStrToObject(CityList.class, getXMLString("citylist.xml"));
            cities = cityList.getCities();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return cities;
    }

    private String getXMLString(String path) {
        Resource resource = new ClassPathResource(path);
        StringBuffer sb = new StringBuffer();
        try {
            InputStream inputStream = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
}
